/* NOTICE
    OpenJaWS - Open Java Weather Station
    
    Copyright (C) 2008 Grant Gardner <grant@lastweekend.com.au>
    
    OpenJaWS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
NOTICE */
package au.com.lastweekend.openjaws.plugins;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import au.com.lastweekend.openjaws.api.Readings;
import au.com.lastweekend.openjaws.api.WeatherPlugin;
import au.com.lastweekend.openjaws.api.WeatherPluginException;
import au.com.lastweekend.openjaws.units.PressureUnit;
import au.com.lastweekend.openjaws.units.RainfallUnit;
import au.com.lastweekend.openjaws.units.TemperatureUnit;
import au.com.lastweekend.openjaws.units.WindUnit;

/**
 * TODO Work in Progress, DO NOT USE
 * @author ggardner
 *
 */
public class WeatherUndergroundPlugin implements WeatherPlugin {

    private static final Logger LOG = LoggerFactory.getLogger(WeatherUndergroundPlugin.class);
    private String wuURI;
    private String wuID;
    private String wuPassword;
    private HttpClient httpClient;

    private String softwareType="OpenJaWS";
    
    public WeatherUndergroundPlugin(HttpClient httpClient, String wuURI, String wuID, String wuPassword) {

        this.httpClient = httpClient;
        this.wuURI = wuURI;
        this.wuID = wuID;
        this.wuPassword = wuPassword;
    }


    public void process(Readings readings) throws WeatherPluginException {

        HttpMethod method = new GetMethod(wuURI);
        HttpMethodParams params = new HttpMethodParams();
        
        params.setParameter("action", "updateraw");
        params.setParameter("ID",wuID);
        params.setParameter("PASSWORD",wuPassword);
        
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        
        params.setParameter("dateutc",df.format(readings.getReadingTime()));
        
        params.setDoubleParameter("windspeedmph", readings.getWindSpeed().getCurrent().convertTo(WindUnit.MILES_PER_HOUR).getValue());
        params.setDoubleParameter("winddir", readings.getWindSpeed().getCurrent().getDirection());
        /*
         * TODO: Average wind info.
         * wind gust, using software specific time period] windgustdir - [0-360 using software specific time period]
         * windspdmph_avg2m - [mph 2 minute average wind speed mph] winddir_avg2m - [0-360 2 minute average wind direction]
         * windgustmph_10m - [mph past 10 minutes wind gust mph ] windgustdir_10m - [0-360 past 10 minutes wind gust direction]
         */
        
        params.setDoubleParameter("humidity", readings.getOutdoorHumidity().getCurrent().getValue());
        params.setDoubleParameter("tempf", readings.getOutdoorTemperature().getCurrent().convertTo(TemperatureUnit.FAHRENHEIT).getValue());
        // for extra outdoor sensors use temp2f, temp3f, and so on
        
        params.setDoubleParameter("rainin", readings.getRain1H().getCurrent().convertTo(RainfallUnit.INCH).getValue());
        // TODO dailyrainin - [rain inches so far today in local time]
        
        params.setDoubleParameter("baromin", readings.getAirPressure().getCurrent().convertTo(PressureUnit.INCHES_OF_MERCURY).getValue());

        params.setDoubleParameter("indoorhumidity", readings.getIndoorHumidity().getCurrent().getValue());
        params.setDoubleParameter("indoortempf", readings.getIndoorTemperature().getCurrent().convertTo(TemperatureUnit.FAHRENHEIT).getValue());

        params.setParameter("softwaretype",getSoftwareType());        
        
        method.setParams(params);
        try {

            int response = httpClient.executeMethod(method);
            if (LOG.isDebugEnabled()) {
                String responseBody = method.getResponseBodyAsString();
                LOG.debug(String.format("WeatherUnderground http response %d\n%s",response,responseBody));                
            }
        } catch (Exception e) {
           LOG.error("Exception executing Http GET",e);
        } finally {
            method.releaseConnection();
        }
        
    }


    
    public String getSoftwareType() {
    
        return softwareType;
    }


    
    public void setSoftwareType(String softwareType) {
    
        this.softwareType = softwareType;
    }
}
